package com.bzkj.basicinfo.service.pick.impl;

import com.bzkj.basicinfo.domain.pick.WmsPickDetailEntity;
import com.bzkj.basicinfo.domain.pick.WmsPickTaskEntity;
import com.bzkj.basicinfo.mapper.pick.WmsPickDetailMapper;
import com.bzkj.basicinfo.mapper.pick.WmsPickTaskMapper;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.page.TableDataInfo;
import com.bzkj.common.utils.DateUtils;
import com.bzkj.basicinfo.service.pick.WmsPickTaskService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WmsPickTaskServiceImpl implements WmsPickTaskService {

    @Autowired
    private WmsPickTaskMapper pickTaskMapper;

    @Autowired
    private WmsPickDetailMapper pickDetailMapper;

    @Override
    public TableDataInfo getPickTaskList(WmsPickTaskEntity entity, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<WmsPickTaskEntity> list = pickTaskMapper.selectPickTaskList(entity);
        PageInfo<WmsPickTaskEntity> pageInfo = new PageInfo<>(list);
        TableDataInfo dataTable = new TableDataInfo();
        dataTable.setCode(200);
        dataTable.setMsg("查询成功");
        dataTable.setRows(list);
        dataTable.setTotal(pageInfo.getTotal());
        return dataTable;
    }

    @Override
    public AjaxResult getPickTaskDetail(Long id) {
        WmsPickTaskEntity task = pickTaskMapper.selectPickTaskById(id);
        if (task == null) return AjaxResult.error("拣货任务不存在");
        List<WmsPickDetailEntity> detailList = pickDetailMapper.selectPickDetailByTaskId(id);
        Map<String, Object> result = new HashMap<>();
        result.put("task", task);
        result.put("detailList", detailList);
        return AjaxResult.success("查询成功", result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createPickTask(WmsPickTaskEntity entity, String operator) {
        try {
            entity.setPickTaskNo("PICK" + DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS));
            entity.setTaskStatus("0");
            entity.setPickedQuantity(BigDecimal.ZERO);
            entity.setCreateBy(operator);
            int rows = pickTaskMapper.insertPickTask(entity);
            return rows > 0 ? AjaxResult.success("创建成功", entity.getPickTaskNo()) : AjaxResult.error("创建失败");
        } catch (Exception e) {
            throw new RuntimeException("创建拣货任务异常：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult confirmPick(Long taskId, BigDecimal pickQuantity, String locationCode, String operator) {
        try {
            WmsPickTaskEntity task = pickTaskMapper.selectPickTaskById(taskId);
            if (task == null) return AjaxResult.error("拣货任务不存在");
            BigDecimal newPicked = task.getPickedQuantity().add(pickQuantity);
            if (newPicked.compareTo(task.getPickQuantity()) > 0) return AjaxResult.error("拣货数量超过计划数量");

            WmsPickDetailEntity detail = new WmsPickDetailEntity();
            detail.setPickTaskId(taskId);
            detail.setPickTaskNo(task.getPickTaskNo());
            detail.setLocationCode(locationCode);
            detail.setPickQuantity(pickQuantity);
            detail.setOperator(operator);
            detail.setOperateTime(new Date());
            detail.setCreateBy(operator);
            pickDetailMapper.insertPickDetail(detail);

            pickTaskMapper.updatePickedQuantity(taskId, newPicked);
            if (newPicked.compareTo(task.getPickQuantity()) >= 0) {
                pickTaskMapper.updateTaskStatus(taskId, "2");
            } else {
                pickTaskMapper.updateTaskStatus(taskId, "1");
            }
            return AjaxResult.success("拣货确认成功");
        } catch (Exception e) {
            throw new RuntimeException("拣货确认异常：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult completeTask(Long id, String operator) {
        try {
            WmsPickTaskEntity task = pickTaskMapper.selectPickTaskById(id);
            if (task == null) return AjaxResult.error("拣货任务不存在");
            if (task.getPickedQuantity().compareTo(task.getPickQuantity()) < 0) return AjaxResult.error("拣货数量未达到要求");
            int rows = pickTaskMapper.updateTaskStatus(id, "2");
            return rows > 0 ? AjaxResult.success("完成成功") : AjaxResult.error("更新失败");
        } catch (Exception e) {
            throw new RuntimeException("完成拣货任务异常：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deletePickTask(Long id, String operator) {
        try {
            WmsPickTaskEntity task = pickTaskMapper.selectPickTaskById(id);
            if (task == null) return AjaxResult.error("拣货任务不存在");
            if (!"0".equals(task.getTaskStatus())) return AjaxResult.error("只有待拣货状态才能删除");
            pickDetailMapper.deletePickDetailByTaskId(id);
            int rows = pickTaskMapper.deletePickTaskById(id);
            return rows > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
        } catch (Exception e) {
            throw new RuntimeException("删除拣货任务异常：" + e.getMessage(), e);
        }
    }
}
